package de.slothsoft.wasbinich.android.control;

import java.io.Serializable;

import android.os.CountDownTimer;

public abstract class CountDown implements Serializable {

    private static final long serialVersionUID = -4942876971281735561L;
    private final long countDownInterval;
    private long millisUntilFinished;

    private Timer delegate;

    public CountDown(long millisInFuture, long countDownInterval) {
	this.millisUntilFinished = millisInFuture;
	this.countDownInterval = countDownInterval;
	this.delegate = new Timer(millisInFuture, countDownInterval);
    }

    public void start() {
	if (this.delegate == null) {
	    resume();
	} else {
	    this.delegate.start();
	}
    }

    protected final void tickDown(long newMillisUntilFinished) {
	this.millisUntilFinished = newMillisUntilFinished;
	onTick(this.millisUntilFinished);
    }

    public abstract void onTick(long millisUntilFinished);

    protected final void finishUp() {
	onFinish();
    }

    public abstract void onFinish();

    public void pause() {
	if (this.delegate != null) {
	    this.delegate.cancel();
	    this.delegate = null;
	}
    }

    public void resume() {
	if (this.delegate == null) {
	    this.delegate = new Timer(this.millisUntilFinished, this.countDownInterval);
	    this.delegate.start();
	}
    }

    public long getMilliSecondsUntilFinished() {
	return this.millisUntilFinished;
    }

    /*
     * 
     */

    class Timer extends CountDownTimer implements Serializable {

	private static final long serialVersionUID = 4166383911436991548L;

	public Timer(long millisInFuture, long countDownInterval) {
	    super(millisInFuture, countDownInterval);
	}

	@Override
	public void onTick(long millisUntilFinished) {
	    tickDown(millisUntilFinished);
	}

	@Override
	public void onFinish() {
	    finishUp();
	}
    };
}
